class SSEManager {
  constructor() {
    this.eventSource = null;
    this.token = null;
    this.subscribers = new Map();
    this.reconnectAttempts = 0;
    this.messageCache = new Map(); // 新增消息缓存
    console.debug('SSEManager 初始化');
    // 实例属性方式声明 SUPPORTED_EVENTS
    this.SUPPORTED_EVENTS = ['update', 'house_sales', 'house_distribution','sales_data','housing_rental_statistics'];
  
  }


  connect(token) {
    if (this.eventSource) {
      console.debug('SSE连接已存在，跳过创建');
      return this;
    }

    this.token = token;
    console.debug('开始建立SSE连接');
    this._createConnection();
    return this;
  }

  _createConnection() {
    console.debug('创建新的SSE连接');
    this.eventSource = new EventSource(`/dev-api/api/sales/sse?token=${this.token}`);

    this.eventSource.onopen = () => {
      this.reconnectAttempts = 0;
      console.debug('SSE连接已建立');
    };

    this.SUPPORTED_EVENTS.forEach(eventType => {
      this.eventSource.addEventListener(eventType, (event) => {
        try {
          const data = JSON.parse(event.data);
          this.dispatch(eventType, data);
        } catch (e) {
          console.error(`[${eventType}] 消息解析失败`, e);
        }
      });
    });

    this.eventSource.onerror = (err) => {
      console.log('SSE连接错误:', err);
      this._reconnect();
    };
  }

  _reconnect() {
    console.debug('开始重连SSE');
    this.close();
    const delay = Math.min(1000 * 2 ** this.reconnectAttempts, 30000);

    setTimeout(() => {
      console.debug(`尝试第${this.reconnectAttempts + 1}次重连`);
      this.reconnectAttempts++;
      this._createConnection();
    }, delay);
  }

  dispatch(eventType, data) {
    console.debug(`[SSE Dispatch] Type: ${eventType}`, data);
    const callbacks = this.subscribers.get(eventType) || [];
    callbacks.forEach(cb => cb(data));
  }

  subscribe(eventType, callback) {
    console.debug(`订阅事件类型: ${eventType}`);
    // 如果已有缓存数据立即触发
    if (this.messageCache.has(eventType)) {
      console.debug(`发现缓存数据，立即触发事件类型: ${eventType}`);
      callback(this.messageCache.get(eventType));
    }

    if (!this.subscribers.has(eventType)) {
      this.subscribers.set(eventType, new Set());
    }

    this.subscribers.get(eventType).add(callback);
    return () => this.unsubscribe(eventType, callback); // 返回取消订阅函数
  }

  unsubscribe(eventType, callback) {
    console.debug(`取消订阅事件类型: ${eventType}`);
    const callbacks = this.subscribers.get(eventType);
    if (callbacks) {
      callbacks.delete(callback);
      if (callbacks.size === 0) {
        this.subscribers.delete(eventType);
        console.debug(`所有订阅者已移除，删除事件类型: ${eventType}`);
      }
    }
  }

  reconnect() {
    console.debug('手动触发重连');
    this.close();
    this.connect(this.token);
  }

  close() {
    if (this.eventSource) {
      console.debug('关闭SSE连接');
      this.eventSource.close();
      this.eventSource = null;
    }
  }
}

export const sseManager = new SSEManager();